package com.github.iogogogo.task.manager.schedule;

import com.github.iogogogo.common.util.Java8DateTimeUtils;
import com.github.iogogogo.common.util.SpringContextUtils;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * Created by tao.zeng on 2021/3/29.
 */
@Slf4j
public class ScheduledTaskUtils {

    /**
     * Trigger.
     *
     * @param beanName   the bean name
     * @param methodName the method name
     * @param param      the param
     */
    public static void trigger(String beanName, String methodName, String param) {

        Stopwatch stopwatch = Stopwatch.createStarted();

        log.debug("trigger schedule task. timestamp:{} beanName:{} methodName:{} param:{}", Java8DateTimeUtils.nowDateTime(), beanName, methodName, param);
        try {
            Object target = SpringContextUtils.getBean(beanName);

            Method method = StringUtils.isNotEmpty(param) ?
                    target.getClass().getDeclaredMethod(methodName, String.class) :
                    target.getClass().getDeclaredMethod(methodName);

            ReflectionUtils.makeAccessible(method);

            if (StringUtils.isNotEmpty(param)) {
                method.invoke(target, param);
            } else {
                method.invoke(target);
            }

            log.debug("trigger scheduler task time consuming: {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.error("trigger scheduler task failure. beanName:{} methodName:{} param:{}", beanName, methodName, param, e);
        }
    }
}
